package com.wisenet.service.wxpubno;

import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wisenet.cache.RedisCacheProvider;
import com.wisenet.common.Const;
import com.wisenet.common.WxConst;
import com.wisenet.dao.UserDAO;
import com.wisenet.dao.wx.MenuInfoDAO;
import com.wisenet.dao.wx.MessageInfoDAO;
import com.wisenet.dao.wx.UserInfoDAO;
import com.wisenet.entity.MenuInfo;
import com.wisenet.entity.MessageInfo;
import com.wisenet.entity.User;
import com.wisenet.entity.UserInfo;
import com.wisenet.util.TencentOssUtil;
import com.wisenet.wx.api.GuessNumber;
import com.wisenet.wx.util.MessageManager;
import com.wisenet.wx.util.MessageUtil;
import com.wisenet.wx.util.StringUtil;

/**
 * 事件服务类
 * @author fzh
 */
@Service
public class EventService {
	// 日志
	private static Logger logger = Logger.getLogger(EventService.class);
	@Autowired
	private UserDAO userDAO;
	@Autowired
	private UserInfoDAO userInfoDAO;
	@Autowired
	private RedisCacheProvider redis;
	@Autowired
	private MenuInfoDAO menuInfoDAO;
	@Autowired
	private MessageInfoDAO messageInfoDAO;
	
	/**
	 * 事件推送
	 * @param requestMap
	 * @return
	 */
	public String operateEventMessage(Map<String, String> requestMap) {
		String eventType = requestMap.get(MessageUtil.EVENT_TYPE).trim();
		String toUserName = requestMap.get(WxConst.TO_USER_NAME);
		String fromUserName = requestMap.get(WxConst.FROM_USER_NAME);
		
		// 自定义菜单点击事件
		if (MessageUtil.EVENT_TYPE_CLICK.equals(eventType)) {
			return replyMessageByClickMenu(requestMap);
		}
		// 已关注用户扫描二维码
		if (MessageUtil.EVENT_TYPE_SCAN.equals(eventType)) {
//			return scanQrCodeEvent();
			logger.info("已关注用户扫描二维码...");
			return MessageUtil.replyTextMessage(fromUserName, toUserName, StringUtil.strContent());
		}
		// 订阅
		if (MessageUtil.EVENT_TYPE_SUBSCRIBE.equals(eventType)) {
			subscribeEvent(toUserName, fromUserName);
			logger.info(fromUserName + " 用户订阅...");
			return MessageUtil.replyTextMessage(fromUserName, toUserName, StringUtil.strContent());
		}
		// 取消订阅
		if (MessageUtil.EVENT_TYPE_UNSUBSCRIBE.equals(eventType)) {
			unsubscribeEvent(fromUserName);
		}
		// 自定义菜单拍照/相册事件
		/*if (eventType.equals(MessageUtil.EVENT_TYPE_PIC_PHOTO_OR_ALBUM)) {
			String eventKey = requestMap.get(MessageUtil.EVENT_KEY).trim();
			logger.info(eventType + " , " + eventKey);
		}*/
		return null;
	}
	
	/**
	 * 点击菜单回复消息
	 * @param requestMap
	 * @return
	 */
	public String replyMessageByClickMenu(Map<String, String> requestMap) {
		// 事件KEY值，与创建自定义菜单时指定的KEY值对应
		String eventKey = requestMap.get(MessageUtil.EVENT_KEY).trim();
		String toUserName = requestMap.get(WxConst.TO_USER_NAME);
		String fromUserName = requestMap.get(WxConst.FROM_USER_NAME);
		
		logger.info("eventKey = " + eventKey);
		
		// 链接事件
		if (eventKey == null) return null;
		
		// 保存消息
		// saveMessageInfo(requestMap, null, null, eventKey, "0");

		UserInfo userInfo = null;
		
		// 保存用户操作记录
		if (eventKey.startsWith(Const.MENU_TYPE_RECORD)) {
			userInfo = saveUserInfoRecord(fromUserName, eventKey);
		}
		
		// 猜图、成语 图文消息
		if (Const.MENU_TYPE_GUESS_IMAGE.equals(eventKey) 
				|| Const.MENU_TYPE_GUESS_IDIOM.equals(eventKey)) {
			return MessageManager.getGuessImageMessage(requestMap, userInfo.getIds());
		}
		
		// 返回菜单提示内容
		MenuInfo menuInfo = menuInfoDAO.findMenuInfo(toUserName, eventKey);
		if (menuInfo != null) {
			if (menuInfo.getRefText() != null) {
				return MessageUtil.replyTextMessage(fromUserName, toUserName, menuInfo.getRefText());
			}
		}
		
		return null;
	}
	
	/**
	 * 保存用户操作记录
	 * 猜图, 翻译, 音乐, 成语, 聊天 , 猜数
	 * @param fromUserName
	 * @param type
	 */
	public UserInfo saveUserInfoRecord(String fromUserName, String type) {
		UserInfo userInfo = userInfoDAO.findByUserIdAndType(fromUserName, type);
		
		// 06重新猜数
		if (userInfo != null && Const.MENU_TYPE_GUESS_NUMBER.equals(userInfo.getType()) 
				&& Const.GUESS_NUMBER_IS_SEND.equals(userInfo.getIsend())) {
			userInfo = null;
		}
		
		// 切换菜单功能
		if (userInfo != null && type.equals(userInfo.getType())) {
			logger.info(" 更新用户操作记录...");
			userInfo.setTime(new Date());
			userInfoDAO.updateUser(userInfo);
		}

		if (userInfo == null) {
			logger.info(" 新增用户操作记录...");
			userInfo = new UserInfo();
			userInfo.setType(type);
			userInfo.setTime(new Date());
			userInfo.setUserid(fromUserName);
			// 猜数答案、猜图关数
			userInfo.setIds(Const.MENU_TYPE_GUESS_NUMBER.equals(type) ? 
					GuessNumber.setAnswer() : Const.GAME_NUM_DEFAULT.toString());
			userInfoDAO.insert(userInfo);
		}
		
		return userInfo;
	}
	
	/**
	 * 用户订阅事件
	 * @param toUserName
	 * @param fromUserName
	 */
	private void subscribeEvent(String toUserName, String fromUserName) {
		User user = userDAO.findByOpenId(fromUserName);
		if (user == null) {
			user = new User();
			user.setOpenid(fromUserName);
			user.setWxpublicno(toUserName);
			user.setCreateTime(new Date());
			userDAO.save(user);
		}
	}
	
	/**
	 * 扫描二维码事件
	 * @return
	 */
	@SuppressWarnings("unused")
	private String scanQrCodeEvent() {
//		String senceid = requestMap.get("EventKey");
//		String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+requestMap.get("Ticket");
//		respContent = senceid+"\n<a href=\""+url+"\">查看二维码</a>";
		return null;
	}
	
	public void saveMessageInfo(Map<String, String> requestMap, Long imageTextNo, 
			String remsgType, String url, String keyword) {
		
		MessageInfo messageInfo = MessageManager.createMessageInfo(requestMap, imageTextNo,
				remsgType, url, keyword);
		
		messageInfoDAO.save(messageInfo);
	}
	
	/**
	 * 用户取消订阅事件
	 * @param uid
	 * @return
	 */
	private void unsubscribeEvent(String uid) {
		// 删除二维码图片
		TencentOssUtil tCloud = new TencentOssUtil();
		tCloud.deleteObjects("ocrweb/" + uid);
		// 删除redis记录
		redis.remove("QR_CODE_" + uid);
		logger.info(uid + " 取关 删除二维码图片、redis记录 ...");
	}
}
